// pages/list/list.js
const fetch = require('../../utils/fetch');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    category: {},
    shops: [],
    pageIndex: 0,
    pageSize: 20,
    hasMore: true
  },
  loadMore () {
    if (!this.data.hasMore) return;
    let {pageIndex, pageSize} = this.data;
    const params = { _page: ++pageIndex, _limit: pageSize}
    return fetch(`categories/${this.data.category.id}/shops`, params)
      .then(res => {
        const totalCount = parseInt(res.header['X-Total-Count']);
        const hasMore = pageIndex * pageSize < totalCount;
        const shops = this.data.shops.concat(res.data);
        this.setData({
          shops,
          pageIndex,
          hasMore
        })
      })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    fetch( `categories/${options.cat}`).then(res => {
      this.setData({
        category: res.data
      })
      wx.setNavigationBarTitle({
        title: res.data.name
      })
      this.loadMore()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    if (this.data.category.name) {
      wx.setNavigationBarTitle({
        title: this.data.category.name
      })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('别拉了，到底了');
    this.loadMore()
  },
  onPullDownRefresh: function () {
    // console.log(123);
    this.setData({
      shops: [],
      pageIndex: 0
    })
    this.loadMore().then(() => {
      wx.stopPullDownRefresh();
    });
  }
})